<?php
/**
 * 小程序系统功能API
 * 处理系统配置、志愿者申请、意见反馈等
 */

require_once 'base.php';

class SystemAPI extends MiniappBase {
    
    /**
     * 获取系统配置
     */
    public function getConfig() {
        try {
            // 获取基础配置
            $sql = "SELECT * FROM system_config WHERE status = 'active'";
            $configs = $this->db->fetchAll($sql);
            
            $configData = [];
            foreach ($configs as $config) {
                $configData[$config['key']] = $config['value'];
            }
            
            // 获取开放时间
            $sql = "SELECT * FROM timeslots WHERE status = 'active' ORDER BY start_time";
            $timeslots = $this->db->fetchAll($sql);
            
            foreach ($timeslots as &$slot) {
                $slot['start_time'] = substr($slot['start_time'], 0, 5);
                $slot['end_time'] = substr($slot['end_time'], 0, 5);
            }
            
            $this->success([
                'museum_name' => $configData['museum_name'] ?? '历史博物馆',
                'museum_description' => $configData['museum_description'] ?? '',
                'contact_phone' => $configData['contact_phone'] ?? '',
                'contact_address' => $configData['contact_address'] ?? '',
                'opening_hours' => $configData['opening_hours'] ?? '9:00-17:00',
                'closed_days' => $configData['closed_days'] ?? '周一',
                'reservation_notice' => $configData['reservation_notice'] ?? '',
                'visit_rules' => $configData['visit_rules'] ?? '',
                'timeslots' => $timeslots,
                'max_advance_days' => intval($configData['max_advance_days'] ?? 7),
                'min_advance_hours' => intval($configData['min_advance_hours'] ?? 2)
            ]);
            
        } catch (Exception $e) {
            $this->error('获取系统配置失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取闭馆日期
     */
    public function getClosures() {
        $year = $_GET['year'] ?? date('Y');
        $month = $_GET['month'] ?? null;
        
        try {
            $sql = "SELECT date, reason FROM closures WHERE status = 'active'";
            $params = [];
            
            if ($month) {
                $sql .= " AND YEAR(date) = ? AND MONTH(date) = ?";
                $params = [$year, $month];
            } else {
                $sql .= " AND YEAR(date) = ?";
                $params = [$year];
            }
            
            $sql .= " ORDER BY date";
            
            $closures = $this->db->fetchAll($sql, $params);
            
            $this->success($closures);
            
        } catch (Exception $e) {
            $this->error('获取闭馆日期失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 提交志愿者申请
     */
    public function submitVolunteerApplication() {
        $user = $this->getCurrentUser();
        $input = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        $required = ['name', 'gender', 'age', 'phone', 'education', 'profession', 'skills', 'available_time'];
        foreach ($required as $field) {
            if (empty($input[$field])) {
                $this->error("缺少必填字段: $field");
            }
        }
        
        try {
            // 检查是否已有申请
            $sql = "SELECT id FROM volunteer_applications 
                    WHERE user_id = ? AND status IN ('pending', 'approved')";
            $existing = $this->db->fetchOne($sql, [$user['id']]);
            
            if ($existing) {
                $this->error('您已提交过志愿者申请，请勿重复申请');
            }
            
            // 生成申请号
            $applicationNo = 'V' . date('Ymd') . sprintf('%04d', rand(1000, 9999));
            
            // 创建申请记录
            $sql = "INSERT INTO volunteer_applications (
                        user_id, name, gender, age, phone, email, id_card, education,
                        profession, skills, experience, available_time, motivation,
                        emergency_contact, application_no, status, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())";
            
            $params = [
                $user['id'],
                $input['name'],
                $input['gender'],
                intval($input['age']),
                $input['phone'],
                $input['email'] ?? '',
                $input['id_card'] ?? '',
                $input['education'],
                $input['profession'],
                $input['skills'],
                $input['experience'] ?? '',
                $input['available_time'],
                $input['motivation'] ?? '',
                $input['emergency_contact'] ?? '',
                $applicationNo
            ];
            
            $this->db->execute($sql, $params);
            $applicationId = $this->db->lastInsertId();
            
            // 记录日志
            $this->logApi('submit_volunteer_application', [
                'user_id' => $user['id'],
                'application_id' => $applicationId
            ]);
            
            $this->success([
                'application_id' => $applicationId,
                'application_no' => $applicationNo,
                'status' => 'pending'
            ], '志愿者申请已提交，我们会尽快审核并与您联系');
            
        } catch (Exception $e) {
            $this->error('提交志愿者申请失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取用户志愿者申请记录
     */
    public function getUserVolunteerApplications() {
        $user = $this->getCurrentUser();
        
        try {
            $sql = "SELECT * FROM volunteer_applications 
                    WHERE user_id = ? 
                    ORDER BY created_at DESC";
            
            $applications = $this->db->fetchAll($sql, [$user['id']]);
            
            // 格式化数据
            foreach ($applications as &$application) {
                $application['created_at'] = $this->formatTime($application['created_at']);
                $application['updated_at'] = $this->formatTime($application['updated_at']);
                $application['reviewed_at'] = $this->formatTime($application['reviewed_at']);
            }
            
            $this->success($applications);
            
        } catch (Exception $e) {
            $this->error('获取志愿者申请记录失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 提交意见反馈（兼容反馈字段）
     */
    public function submitFeedback() {
        $user = $this->getCurrentUser();
        $input = json_decode(file_get_contents('php://input'), true) ?: [];
    
        // 字段映射与默认值
        $title = trim($input['title'] ?? ($input['subject'] ?? ''));
        $content = trim($input['content'] ?? ($input['message'] ?? ''));
        $type = $input['type'] ?? $input['feedback_type'] ?? 'other';
        $contact = $input['contact_info'] ?? $input['contact_phone'] ?? ($input['phone'] ?? '');
        $images = $input['images'] ?? [];
    
        // 处理 images：允许数组/JSON字符串/逗号分隔
        if (is_string($images)) {
            $decoded = json_decode($images, true);
            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                $images = $decoded;
            } else {
                $images = array_values(array_filter(array_map('trim', explode(',', $images))));
            }
        }
        if (!is_array($images)) {
            $images = [];
        }
    
        // 校验
        if ($content === '') {
            $this->error('反馈内容不能为空');
        }
        if (mb_strlen($title) > 100) {
            $this->error('标题长度不能超过100个字符');
        }
        if (mb_strlen($content) > 2000) {
            $this->error('反馈内容不能超过2000个字符');
        }
        if (!empty($contact) && !preg_match('/^1[3-9]\d{9}$/', $contact)) {
            // contact 兼容手机号校验；若为非手机号也允许，但给出更宽松提示
            // 如需严格手机号，可取消以下宽松逻辑
            // $this->error('手机号格式不正确');
        }
    
        // 检测表结构，进行自适应写入
        try {
            $cols = $this->db->fetchAll("SHOW COLUMNS FROM feedback");
            $colNames = array_map(function ($c) { return $c['Field'] ?? $c['field'] ?? ''; }, $cols);
    
            $typeCol = in_array('feedback_type', $colNames, true) ? 'feedback_type' : (in_array('type', $colNames, true) ? 'type' : null);
            $contactCol = in_array('contact_phone', $colNames, true) ? 'contact_phone' : (in_array('contact_info', $colNames, true) ? 'contact_info' : null);
            $hasUpdatedAt = in_array('updated_at', $colNames, true);
            $hasCreatedAt = in_array('created_at', $colNames, true);
            $statusIsInt = false;
            if (in_array('status', $colNames, true)) {
                // 获取 status 列类型，粗略判断是否为 int
                $statusDef = $this->db->fetchAll("SHOW COLUMNS FROM feedback LIKE 'status'");
                $typeDef = $statusDef[0]['Type'] ?? $statusDef[0]['type'] ?? '';
                $statusIsInt = stripos($typeDef, 'int') !== false || stripos($typeDef, 'tinyint') !== false || stripos($typeDef, 'smallint') !== false;
            }
    
            // 组装字段和值
            $fields = ['user_id', 'title', 'content', 'images'];
            $params = [$user['id'], $title, $content, json_encode($images, JSON_UNESCAPED_UNICODE)];
            if ($typeCol) {
                $fields[] = $typeCol;
                $params[] = $type;
            }
            if ($contactCol) {
                $fields[] = $contactCol;
                $params[] = $contact;
            }
    
            if (in_array('status', $colNames, true)) {
                $fields[] = 'status';
                $params[] = $statusIsInt ? 0 : 'pending';
            }
            if ($hasCreatedAt) {
                $fields[] = 'created_at';
                $params[] = date('Y-m-d H:i:s');
            }
            if ($hasUpdatedAt) {
                $fields[] = 'updated_at';
                $params[] = date('Y-m-d H:i:s');
            }
    
            $columnsSql = implode(', ', $fields);
            $placeholders = implode(', ', array_fill(0, count($fields), '?'));
            $sql = "INSERT INTO feedback ($columnsSql) VALUES ($placeholders)";
    
            $this->db->execute($sql, $params);
            $feedbackId = $this->db->lastInsertId();
    
            // 记录日志
            $this->logApi('submit_feedback', [
                'user_id' => $user['id'],
                'feedback_id' => $feedbackId,
                'type' => $type
            ]);
    
            $this->success([
                'feedback_id' => $feedbackId,
                'title' => $title,
                'feedback_type' => $type,
                'status' => $statusIsInt ? 'pending' : 'pending',
                'message' => '您的意见反馈已提交成功，我们会尽快处理'
            ], '意见反馈提交成功');
        } catch (Exception $e) {
            $this->error('提交反馈失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取用户反馈记录
     */
    public function getUserFeedback() {
        $user = $this->getCurrentUser();
        $pagination = $this->paginate($_GET['page'] ?? 1, $_GET['limit'] ?? 10);
        
        try {
            $sql = "SELECT id, type, title, content, status, created_at, updated_at, reply
                    FROM feedback 
                    WHERE user_id = ? 
                    ORDER BY created_at DESC 
                    LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}";
            
            $feedback = $this->db->fetchAll($sql, [$user['id']]);
            
            // 获取总数
            $countSql = "SELECT COUNT(*) as total FROM feedback WHERE user_id = ?";
            $total = $this->db->fetchOne($countSql, [$user['id']])['total'];
            
            // 格式化数据
            foreach ($feedback as &$item) {
                $item['created_at'] = $this->formatTime($item['created_at']);
                $item['updated_at'] = $this->formatTime($item['updated_at']);
                
                // 反馈类型中文名称
                $typeNames = [
                    'suggestion' => '建议',
                    'complaint' => '投诉',
                    'praise' => '表扬',
                    'bug_report' => '问题反馈',
                    'other' => '其他'
                ];
                $item['type_name'] = $typeNames[$item['type']] ?? $item['type'];
            }
            
            $this->success([
                'list' => $feedback,
                'pagination' => [
                    'page' => $pagination['page'],
                    'limit' => $pagination['limit'],
                    'total' => intval($total),
                    'pages' => ceil($total / $pagination['limit'])
                ]
            ]);
            
        } catch (Exception $e) {
            $this->error('获取反馈记录失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取常见问题
     */
    public function getFAQ() {
        $category = $_GET['category'] ?? null;
        
        try {
            $sql = "SELECT id, question, answer, category, sort FROM faq WHERE status = 'active'";
            $params = [];
            
            if ($category) {
                $sql .= " AND category = ?";
                $params[] = $category;
            }
            
            $sql .= " ORDER BY sort ASC, id ASC";
            
            $faq = $this->db->fetchAll($sql, $params);
            
            $this->success($faq);
            
        } catch (Exception $e) {
            $this->error('获取常见问题失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取FAQ分类
     */
    public function getFAQCategories() {
        try {
            $sql = "SELECT DISTINCT category FROM faq 
                    WHERE status = 'active' AND category IS NOT NULL AND category != ''
                    ORDER BY category";
            
            $categories = $this->db->fetchAll($sql);
            
            $this->success($categories);
            
        } catch (Exception $e) {
            $this->error('获取FAQ分类失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 记录用户访问统计
     */
    public function recordVisit() {
        $user = $this->getCurrentUser();
        $input = json_decode(file_get_contents('php://input'), true);
        
        try {
            $sql = "INSERT INTO user_visits (
                        user_id, page, action, ip, user_agent, created_at
                    ) VALUES (?, ?, ?, ?, ?, NOW())";
            
            $params = [
                $user['id'],
                $input['page'] ?? '',
                $input['action'] ?? '',
                $_SERVER['REMOTE_ADDR'] ?? '',
                $_SERVER['HTTP_USER_AGENT'] ?? ''
            ];
            
            $this->db->execute($sql, $params);
            
            $this->success(null, '访问记录成功');
            
        } catch (Exception $e) {
            // 访问统计失败不应影响主要功能
            $this->success(null, '访问记录完成');
        }
    }
}

// 处理请求
$system = new SystemAPI();

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'config':
                $system->getConfig();
                break;
            case 'closures':
                $system->getClosures();
                break;
            case 'volunteer_applications':
                $system->getUserVolunteerApplications();
                break;
            case 'feedback':
                $system->getUserFeedback();
                break;
            case 'feedback_types':
                // 新增：获取反馈类型（兼容）
                $system->getFeedbackTypes();
                break;
            case 'feedback_stats':
                // 新增：获取反馈统计（兼容）
                $system->getFeedbackStats();
                break;
            case 'faq':
                $system->getFAQ();
                break;
            case 'faq_categories':
                $system->getFAQCategories();
                break;
            default:
                $system->error('无效的操作');
        }
        break;

    case 'POST':
        switch ($action) {
            case 'volunteer_apply':
                $system->submitVolunteerApplication();
                break;
            case 'feedback':
                $system->submitFeedback();
                break;
            case 'visit':
                $system->recordVisit();
                break;
            default:
                $system->error('无效的操作');
        }
        break;
        
    default:
        $system->error('不支持的请求方法');
}
?>

/**
 * 获取反馈类型（与 feedback.php 对齐）
 */
public function getFeedbackTypes() {
    try {
        $types = [
            ['type' => '服务反馈', 'description' => '对展览服务的意见和建议'],
            ['type' => '展览反馈', 'description' => '对展览内容的意见和建议'],
            ['type' => '设施反馈', 'description' => '对博物馆设施的意见和建议'],
            ['type' => '活动反馈', 'description' => '对博物馆活动的意见和建议'],
            ['type' => '网站反馈', 'description' => '对网站功能的意见和建议'],
            ['type' => '其他反馈', 'description' => '其他意见和建议'],
            ['type' => '投诉建议', 'description' => '投诉和改进建议'],
            ['type' => '表扬感谢', 'description' => '表扬和感谢']
        ];
        $this->success(['feedback_types' => $types]);
    } catch (Exception $e) {
        $this->error('获取反馈类型失败: ' . $e->getMessage());
    }
}

/**
 * 获取反馈统计（与 feedback.php 对齐，自适应表结构）
 */
public function getFeedbackStats() {
    $user = $this->getCurrentUser();
    try {
        // 检测列名，用于类型统计
        $cols = $this->db->fetchAll("SHOW COLUMNS FROM feedback");
        $colNames = array_map(function ($c) { return $c['Field'] ?? $c['field'] ?? ''; }, $cols);
        $typeCol = in_array('feedback_type', $colNames, true) ? 'feedback_type' : (in_array('type', $colNames, true) ? 'type' : null);
    
        // 统计总数、待处理、已处理、最近反馈日期
        $sql = "SELECT 
                    COUNT(*) as total_feedbacks,
                    SUM(CASE WHEN (status = 'pending' OR status = 0) THEN 1 ELSE 0 END) as pending_count,
                    SUM(CASE WHEN (status = 'processed' OR status = 1) THEN 1 ELSE 0 END) as processed_count,
                    DATE(MAX(created_at)) as latest_feedback_date
                FROM feedback 
                WHERE user_id = ?";
        $stats = $this->db->fetchOne($sql, [$user['id']]);
    
        // 类型分布
        $types = [];
        if ($typeCol) {
            $typeSql = "SELECT $typeCol as feedback_type, COUNT(*) as count 
                        FROM feedback 
                        WHERE user_id = ? 
                        GROUP BY $typeCol";
            $types = $this->db->fetchAll($typeSql, [$user['id']]);
        }
    
        $this->success([
            'total_feedbacks' => intval($stats['total_feedbacks'] ?? 0),
            'pending_count' => intval($stats['pending_count'] ?? 0),
            'processed_count' => intval($stats['processed_count'] ?? 0),
            'latest_feedback_date' => $stats['latest_feedback_date'] ?? null,
            'feedback_types' => $types
        ]);
    } catch (Exception $e) {
        $this->error('获取统计信息失败: ' . $e->getMessage());
    }
}